import { ConfigEnv, UserConfig, defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import eslintPlugin from 'vite-plugin-eslint'

import path from 'path'

import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { VantResolver } from '@vant/auto-import-resolver'

const CWD = process.cwd()

// https://vitejs.dev/config/
export default ({ mode }: ConfigEnv): UserConfig => {
  const {
    VITE_BASE_URL,
    VITE_PROXY_URL
    // NODE_ENV
  } = loadEnv(mode, CWD)
  return defineConfig({
    plugins: [
      vue(),
      eslintPlugin({
        cache: false
      }),
      AutoImport({
        resolvers: [VantResolver()]
      }),
      Components({
        resolvers: [VantResolver()]
      })
    ],
    resolve: {
      alias: [
        {
          find: /@\//,
          replacement: path.resolve(__dirname, 'src') + '/'
        }
      ]
    },

    // 添加CSS配置
    // css: {
    // },

    publicDir: 'assets',
    esbuild: {
      drop: ['console', 'debugger']
    },
    build: {
      outDir: 'dist',
      rollupOptions: {
        // https://rollupjs.org/configuration-options/
        output: {
          entryFileNames: 'js/[name]-[hash].js', // 入口文件输出的文件夹名称
          chunkFileNames: 'js/[name]-[hash].js', //chunk包输出的文件夹名称
          assetFileNames: '[ext]/[name]-[hash].[ext]' //静态文件输出的文件夹名称
        }
      }
    },
    base: VITE_BASE_URL,
    server: {
      port: 10001,
      host: '0.0.0.0',
      // open: true,
      strictPort: true, // 为 true 时若端口已被占用则会直接退出，而不是尝试下一个可用端口。
      proxy: {
        '/api': {
          // target: 'http://suyupei.cn:10001',
          // target: 'http://localhost:3000/',
          target: VITE_PROXY_URL,
          changeOrigin: true,
          rewrite: (path) => {
            return path.replace(/^\/api/, '/api')
          }
        }
      }
    },
    define: {
      __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: true
    }
  })
}

// server {
//   listen 80 default_server;
//   server_name your_domain.com; # 替换为你的域名

//   root /var/www/html; # 假设前端静态文件存放于此目录
//   index index.html index.htm;

//   location / {
//       try_files $uri $uri/ /index.html;
//   }

//   # 添加这部分来处理/api的请求转发
//   location /api {
//       proxy_pass http://www.suyupei.cn:3000; # 你的后端服务地址
//       proxy_set_header Host $host;
//       proxy_set_header X-Real-IP $remote_addr;
//       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
//   }
// }
